#!/bin/bash

# Staging环境启动脚本
# 用于在本地启动完整的staging环境

echo "🚀 启动CU MR BULL Staging环境..."

# 检查Node.js版本
if ! command -v node &> /dev/null; then
    echo "❌ Node.js未安装，请先安装Node.js"
    exit 1
fi

echo "📋 Node.js版本: $(node --version)"
echo "📋 npm版本: $(npm --version)"

# 设置环境变量
export NODE_ENV=staging
export APP_ENV=staging

# 创建日志目录
mkdir -p logs/staging

# 函数：启动后端服务
start_backend() {
    echo "🔧 启动后端服务 (端口: 3001)..."
    cd backend
    
    # 检查依赖
    if [ ! -d "node_modules" ]; then
        echo "📦 安装后端依赖..."
        npm install
    fi
    
    # 复制staging环境配置
    cp .env.staging .env
    
    # 启动后端服务
    echo "🚀 启动后端API服务..."
    npm run start:staging > ../logs/staging/backend.log 2>&1 &
    BACKEND_PID=$!
    echo $BACKEND_PID > ../.staging_backend_pid
    
    echo "✅ 后端服务已启动 (PID: $BACKEND_PID)"
    cd ..
}

# 函数：启动前端管理系统
start_admin() {
    echo "🔧 启动管理系统前端 (端口: 5174)..."
    cd admin
    
    # 检查依赖
    if [ ! -d "node_modules" ]; then
        echo "📦 安装前端依赖..."
        npm install
    fi
    
    # 复制staging环境配置
    cp .env.staging .env.local
    
    # 启动前端开发服务器
    echo "🚀 启动管理系统前端..."
    npm run dev -- --port 5174 > ../logs/staging/admin.log 2>&1 &
    ADMIN_PID=$!
    echo $ADMIN_PID > ../.staging_admin_pid
    
    echo "✅ 管理系统前端已启动 (PID: $ADMIN_PID)"
    cd ..
}

# 函数：等待服务启动
wait_for_service() {
    local url=$1
    local name=$2
    local max_attempts=30
    local attempt=1
    
    echo "⏳ 等待 $name 启动..."
    
    while [ $attempt -le $max_attempts ]; do
        if curl -s $url > /dev/null 2>&1; then
            echo "✅ $name 已就绪"
            return 0
        fi
        
        echo "   尝试 $attempt/$max_attempts..."
        sleep 2
        attempt=$((attempt + 1))
    done
    
    echo "❌ $name 启动超时"
    return 1
}

# 主启动流程
main() {
    # 检查是否已有staging环境在运行
    if [ -f ".staging_backend_pid" ] || [ -f ".staging_admin_pid" ]; then
        echo "⚠️  检测到staging环境可能正在运行"
        echo "   如需重新启动，请先运行: ./stop-staging.sh"
        read -p "是否继续启动? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
    
    # 启动服务
    start_backend
    sleep 3
    start_admin
    
    # 等待服务就绪
    echo "\n🔍 检查服务状态..."
    wait_for_service "http://localhost:3001/health" "后端API服务"
    wait_for_service "http://localhost:5174" "管理系统前端"
    
    echo "\n🎉 Staging环境启动完成!"
    echo "📊 服务地址:"
    echo "   • 后端API: http://localhost:3001"
    echo "   • 管理系统: http://localhost:5174"
    echo "   • API文档: http://localhost:3001/api-docs"
    echo "   • 健康检查: http://localhost:3001/health"
    
    echo "\n📝 日志文件:"
    echo "   • 后端日志: logs/staging/backend.log"
    echo "   • 前端日志: logs/staging/admin.log"
    
    echo "\n🛑 停止服务: ./stop-staging.sh"
    echo "📊 查看日志: tail -f logs/staging/backend.log"
    
    # 测试登录接口
    echo "\n🧪 测试登录接口..."
    sleep 2
    curl -X POST http://localhost:3001/api/auth/login \
        -H "Content-Type: application/json" \
        -d '{"email":"admin@example.com","password":"123456"}' \
        -w "\n状态码: %{http_code}\n" 2>/dev/null
}

# 执行主函数
main